import jwtDecode from 'jwt-decode';

/**
 * Decode the JWT token and extract the id
 * @param {string} token - JWT token
 * @returns {string|null} - Extracted id or null if decoding fails
 */
export function getIdFromToken(token) {
    try {
        const decodedToken = jwtDecode(token);
        return decodedToken.id || null;
    } catch (error) {
        console.error('Failed to decode token:', error);
        return null;
    }
}

// base64.js - 一个简单的 Base64 解码函数
function base64Decode(str) {
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var output = '';
    var index = 0;
    var c1, c2, c3, e1, e2, e3, e4;

    while (index < str.length) {
        e1 = chars.indexOf(str.charAt(index++));
        e2 = chars.indexOf(str.charAt(index++));
        e3 = chars.indexOf(str.charAt(index++));
        e4 = chars.indexOf(str.charAt(index++));

        c1 = (e1 << 2) | (e2 >> 4);
        output += String.fromCharCode(c1);

        if (e3 !== 64) {
            c2 = ((e2 & 15) << 4) | (e3 >> 2);
            output += String.fromCharCode(c2);
        }
        if (e4 !== 64) {
            c3 = (e3 & 3) | (e4 << 6);
            output += String.fromCharCode(c3);
        }
    }
    return output;
}

// jwtHelper.js - JWT 解析函数
function parseHS256JWT(token) {
    const base64Payload = token.split('.')[1];
    const decodedPayload = base64Decode(base64Payload);

    try {
        const payload = JSON.parse(decodedPayload);
        return payload;
    } catch (error) {
        console.error('Error parsing JWT payload:', error);
        return null;
    }
}

export default {
    parseHS256JWT
};